/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package qrlogin;

import java.util.List;
import qrlogin.common.QRLoginParameters;
import qrlogin.common.QRLoginParam;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *
 * @author adee
 */
public class QRLoginServlet extends HttpServlet {
    private QRLoginImageManager qrImageManager;
    private QRLoginServletParameters servletParameters;
    private QRLoginOnLoginCheckListener loginCheckListener;
    private QRLoginOnLoginListener loginListener;
    private QRLoginOnLogoutListener logoutListener;
    private QRLoginJQueryLoginChecker checker;




    private void addClientLoginBlock(HttpServletRequest request,HttpServletResponse response) throws IOException {
            QRLoginImage qrImage = this.qrImageManager.getQRLoginImage(request.getSession().getId());
            PrintWriter writer  = response.getWriter();
            writer.println("<div id=\"qrlogin-client-login-block\">");
            writer.println(this.checker.getLoginer());
            if (!this.loginCheckListener.isLogined(request)){
                  writer.println("<div id=\"qrlogin-image\" ><img src=\""+qrImage.getImageSrc()+"\" /></div>");
            } else {
                 writer.println("<div id=\"qr-login-user\" >Bejelentkezve</div>");

            }
            writer.println("</div>");
    }

    public QRLoginServletParameters getServletParameters() {
        return servletParameters;
    }

    public void setServletParameters(QRLoginServletParameters servletParameters) {
        this.servletParameters = servletParameters;
    }
    

    private void addXMLToResponse(HttpServletResponse response) throws IOException{
        PrintWriter writer = response.getWriter();
        writer.print(this.servletParameters.getParameters().buildParameterXML());
    }

    private void loginPassed(HttpServletResponse response) throws IOException{
        PrintWriter writer = response.getWriter();
        writer.print("PASSED");
        writer.println(this.servletParameters.getLoginPassedMessage());


    }

    private void loginFailed(HttpServletResponse response,List<String> errors) throws IOException{
        PrintWriter writer = response.getWriter();
        writer.print("FAILED");
        writer.println(this.servletParameters.getLoginFailedMessage());

        for (String error : errors){
            writer.println(error);
        }
    }

    private void addLoginedStatus(boolean status,HttpServletResponse response) throws IOException{
        PrintWriter writer = response.getWriter();
        writer.print(status?"TRUE":"FALSE");
    }

    private void addClientCommand(HttpServletRequest request,HttpServletResponse response) throws IOException{
         PrintWriter writer = response.getWriter();
         Boolean lastLoginStatus = (Boolean) request.getSession().getAttribute("QRLOGIN_LAST_LOGIN_STATUS");
         if (lastLoginStatus==null) lastLoginStatus = false;

         boolean currentLoginStatus = this.loginCheckListener.isLogined(request);
         if (currentLoginStatus!=lastLoginStatus){
             if (currentLoginStatus)
                 writer.print("LOGIN");
             else
                 writer.print("LOGOUT");
         } else {
             writer.print("KEEP_ALIVE");
         }
        
         lastLoginStatus = currentLoginStatus;
         request.getSession().setAttribute("QRLOGIN_LAST_LOGIN_STATUS", lastLoginStatus);
         System.out.println("get command");
    }

    private void addLogout(HttpServletRequest request, HttpServletResponse response) throws IOException{
       boolean logoutSuccess =  this.logoutListener.onLogout(request);
       response.getWriter().print(logoutSuccess?"SUCCESS":"UNSUCCESS");
    }

    public QRLoginServlet() {
        super();
        this.servletParameters= new QRLoginServletParameters();
        servletParameters.setLoginLink("NO LOGIN LINK SPECIFIED");
        servletParameters.setClientCheckInterval(3000);
        this.qrImageManager = new QRLoginImageManager(this);
        this.setUpDefaultLoginParameters();
        this.setUpDefaultListeners();
        this.checker = new QRLoginJQueryLoginChecker(this);
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        servletParameters.setTempDir(this.getServletContext().getRealPath("temp"));
        servletParameters.setContextPath(this.getServletContext().getContextPath());
    }
    private void setUpDefaultLoginParameters(){
        QRLoginParameters parameters = new QRLoginParameters();
        parameters.addParam(new QRLoginParam("username","Felhasznalo nev"));
        parameters.addParam(new QRLoginParam("password","Jelszo","PASSWORD"));
        this.servletParameters.setParameters(parameters);   
    }
    private void setUpDefaultListeners(){
        this.loginCheckListener= (new QRLoginOnLoginCheckListener() {

            @Override
            public boolean isLogined(HttpServletRequest request) {
                return false;
            }
        });

        this.loginListener = (new QRLoginOnLoginListener() {

            @Override
            public boolean onLogin(HttpServletRequest request, List<String> errors) {
               return false;
            }
        });

       this.logoutListener = (new QRLoginOnLogoutListener() {

            @Override
            public boolean onLogout(HttpServletRequest request) {
               return true;
            }
        });
        
    }


    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String op = request.getParameter("op");
        if (op!=null) {
           if (op.equals("INCLUDE_LOGIN_BLOCK"))
            this.addClientLoginBlock(request, response);
           if (op.equals("SHOW_INFO"))
            this.addXMLToResponse(response);
           if (op.equals("IS_LOGINED"))
              this.addLoginedStatus(this.loginCheckListener.isLogined(request), response);
           if (op.equals("GET_COMMAND"))
              this.addClientCommand(request,response);
           if (op.equals("DO_LOGOUT")){
              this.addLogout(request, response);
           }

           
        }  
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String op = request.getParameter("op");
        if (op==null) return;
        if (op.equals("DO_LOGIN")){
         ArrayList<String> errors = new ArrayList<String>();
         boolean isLogined= this.loginListener.onLogin(request,errors);
             if (isLogined){
                 this.loginPassed(response);
             } else {
                 this.loginFailed(response, errors);
             }

        }

    }

    public QRLoginOnLoginCheckListener getLoginCheckListener() {
        return loginCheckListener;
    }

    public void setLoginCheckListener(QRLoginOnLoginCheckListener loginCheckListener) {
        this.loginCheckListener = loginCheckListener;
    }

    public QRLoginOnLoginListener getLoginListener() {
        return loginListener;
    }

    public QRLoginOnLogoutListener getLogoutListener() {
        return logoutListener;
    }

    public void setLogoutListener(QRLoginOnLogoutListener logoutListener) {
        this.logoutListener = logoutListener;
    }

    public void setLoginListener(QRLoginOnLoginListener loginListener) {
        this.loginListener = loginListener;
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "QRLoginServlet";
    }

}
